import { VFC, useRef, useEffect, useState } from "react";
import { Drawer } from 'antd'
import cls from './index.module.less';
import { imgs } from './faker';
import { AddForm } from './add-form';
import { FilterForm } from './filter-form';
import { LazyImage, ImagePreview } from "zw-components";
function random(min: number, max: number) {
    return Math.floor(Math.random()*(max-min))+min;
}
type ImageInfoStruct = {
    src: string;
    height: number;
    width: number;
}
const defaultImageWidth = 200;
const splitSize = 20;
const ImageBlock: VFC = () => {
    return <div></div>
}
const PhotoPage: VFC<{}> = () => {
    let contentRef =  useRef<HTMLDivElement|null>(null);
    const [size, setSize] = useState(0);
    const [imgCols, setImgCols] = useState<any[]>([]);
    const [loadedImages, setLoadedImages] = useState<ImageInfoStruct[]>([]);
    const notRenderImages = useRef<ImageInfoStruct[]>([]);
    const [_, reload] = useState({});
    useEffect(() => {
        const listener = () => {
            let _size = contentRef.current?.clientWidth;
            setSize(_size ? _size : 0);
        }
        window.addEventListener('resize', listener);
        return () => {
            window.removeEventListener('resize', listener);
        };
    }, []);
    useEffect(() => {
        if(contentRef.current) {
            setSize(contentRef.current.clientWidth);
        }
    }, [contentRef.current])
    useEffect(() => {
        let maxColLen = Math.floor(size / (defaultImageWidth + splitSize));
        console.warn(maxColLen)
        let cols: any = [];
        for(let i = 0; i < maxColLen; i++) {
            cols.push({
                currentHeight: 0,
                imgs: []
            });
        }
        const findMinHeight = () => {
            let result = cols[0];
            for(let item of cols) {
                if(item.currentHeight < result.currentHeight) {
                    result = item;
                }
            }
            return result;
        }
        if(cols.length > 0) {
            for(let item of loadedImages) {
                let result = findMinHeight();
                result.imgs.push(item);
                result.currentHeight += item.height;
            }
        }
        setImgCols(cols);
    }, [size]);
    const findMinColRef = useRef<any>();
    findMinColRef.current = () => {
        if(imgCols.length === 0) {
            return null;
        }
        let result = imgCols[0];
        for(let i = 1; i < imgCols.length; i++) {
            if(imgCols[i].currentHeight < result.currentHeight) {
                result = imgCols[i];
            }
        }
        return result;
    }
    useEffect(() => {
        if(imgCols.length === 0) {
            return;
        }
        for(let item of notRenderImages.current) {
            let result = findMinColRef.current();
            // console.log(result)
            if(result) {
                result.imgs.push(item);
                result.currentHeight += item.height;
                loadedImages.push(item);
            }
        }
        while(notRenderImages.current.length > 0) {
            notRenderImages.current.pop();
        }
        setLoadedImages([...loadedImages])
        setImgCols(imgCols);
    }, [notRenderImages.current]);
    useEffect(() => {
        setTimeout(() => {
            
            let images = imgs.map(item => {
                return {
                    src: item,
                    height: random(100,500),
                    width: random(200,500)
                }
            });
            notRenderImages.current = images;
            reload({})
        });
    }, []);
    const [visiblePreview, setVisiblePreview] = useState(false);
    return (
        <>
            <div className={cls.container}>
                <div className={cls.header}>
                    <AddForm className={cls.operateItem}/>
                    <FilterForm className={cls.operateItem} value={{}} onChange={() => {}}/>
                </div>
                <div className={cls.content} ref={contentRef}>
                    {imgCols.map((cols, idx) => {
                        return (
                            <div key={idx} className={cls.col} style={{width: defaultImageWidth+'px'}}>
                                {cols.imgs.map((img: any, imgIdx: any) => {
                                    return (
                                        <div key={imgIdx} className={cls.imgContainer} style={{width: defaultImageWidth+'px'}} onClick={() => setVisiblePreview(true)}>
                                            <LazyImage key={imgIdx} src={img.src} style={{width: defaultImageWidth+'px', minHeight: '100px'}} tag="img"/>
                                        </div>
                                    )
                                })}
                            </div>
                        )
                    })}
                </div>
            </div>
            <ImagePreview visible={visiblePreview} onClose={() =>setVisiblePreview(false) }/>
        </>
        
    );
}

export default PhotoPage;